﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows;
using System.Windows.Controls;

namespace DataFileApplication_WPF.Extensions
{
    public static class TreeViewExtensions
    {
        // 展开 TreeView 所有节点的方法
        public static void ExpandAllNodes(this TreeView treeView)
        {
            foreach (object item in treeView.Items)
            {
                if (treeView.ItemContainerGenerator.ContainerFromItem(item) is TreeViewItem treeViewItem)
                {
                    ExpandSubNodes(treeViewItem);
                    treeViewItem.IsExpanded = true;
                }
            }
        }

        // 折叠 TreeView 所有节点的方法
        public static void CollapseAllNodes(this TreeView treeView)
        {
            foreach (object item in treeView.Items)
            {
                if (treeView.ItemContainerGenerator.ContainerFromItem(item) is TreeViewItem treeViewItem)
                {
                    CollapseSubNodes(treeViewItem);
                    treeViewItem.IsExpanded = false;
                }
            }
        }

        // 递归展开子节点的方法
        private static void ExpandSubNodes(TreeViewItem parentItem)
        {
            foreach (object childItem in parentItem.Items)
            {
                if (parentItem.ItemContainerGenerator.ContainerFromItem(childItem) is TreeViewItem childTreeViewItem)
                {
                    ExpandSubNodes(childTreeViewItem);
                    childTreeViewItem.IsExpanded = true;
                }
            }
        }

        // 递归折叠子节点的方法
        private static void CollapseSubNodes(TreeViewItem parentItem)
        {
            foreach (object childItem in parentItem.Items)
            {
                if (parentItem.ItemContainerGenerator.ContainerFromItem(childItem) is TreeViewItem childTreeViewItem)
                {
                    CollapseSubNodes(childTreeViewItem);
                    childTreeViewItem.IsExpanded = false;
                }
            }
        }
    }
}
